/****************************************************************
 * <strong>MFPath系统路径处理类</strong>
 * <p>
 * 系统路径获取的相关方法
 * </p>
 *
 * @author AndyZhang 2011
 * @version 0.1
 * ToDo:
 ***************************************************************/
package com.thinkwide.data.core;

import com.thinkwide.data.debug.MFDM;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;


public class MFPath {

    public static String fseparator = File.separator;
    public static char fseparatorchar = File.separatorChar;
    public static String useparator = "/";
    public static char useparatorChar = '/';

    public static String getRealFilePath(HttpServletRequest request) {
        ServletContext application = request.getSession().getServletContext();
        String path = application.getRealPath(request.getServletPath());
        return path;

    }

    public static String getRealFilePath(HttpServletRequest request, String fileName) {

        String path = getRealDirPath(request);
        return path + fseparatorchar + fileName;

    }

    public static String getURLFilePath(HttpServletRequest request) {
        String path = request.getRequestURI();
        path = MFPath.getURLParentPath(path);
        return path + useparator;
    }

    public static String getURLFilePath(HttpServletRequest request, String fileName) {
        String path = request.getRequestURI();
        path = MFPath.getURLParentPath(path);
        return path + useparator + fileName;
    }

    public static String getRealDirPath(HttpServletRequest request) {
        ServletContext application = request.getSession().getServletContext();
        String path = application.getRealPath(request.getServletPath());
        path = getParentPath(path);
        return path;

    }

    public static String getFileExt(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }


    public static String getParentPath(String path) {
        File file = new File(path);
        return file.getParent();
    }

    public static String getURLParentPath(String path) {
        String str = getParentPath(path);
        str = str.replace(fseparatorchar, useparatorChar);
        return str;
    }

    public static String calcUrlPath(String parentPath, String childPath) {
        return calcUrlPath(parentPath, childPath, false);
    }


    public static String calcRealToUrlPath(String webRealPath, String fileRealPath) {
        String path = fileRealPath.substring(webRealPath.length() - 1, fileRealPath.length());
        return path;
    }

    /**
     * @param parentPath 含文件
     * @param childPath  含文件
     * @param returnDir
     * @return
     */
    public static String calcUrlPath(String parentPath, String childPath, boolean returnDir) {
        parentPath = parentPath.replace(fseparator, "|");
        childPath = childPath.replace(fseparator, "|");

        parentPath = parentPath.replace(useparator, "|");
        childPath = childPath.replace(useparator, "|");
        MFDM.X().println(parentPath);
        MFDM.X().println(childPath);
        String[] parent = parentPath.split("\\|");
        String[] child = childPath.split("\\|");

        String prePath = "";
        String relPath = "";
        int index = 0;
        int i = 0;

        while (i < parent.length) {

            if (!MFString.compareNoCase(parent[i], child[i])) {
                index = i;
                break;
            }
            index = i + 1;
            i++;
        }

        i = index;
        while (i < parent.length) {
            prePath = prePath + ".." + MFPath.useparator;
            i++;
        }

        i = index;
        while (i < child.length) {
            if (i != child.length - 1)
                relPath = relPath + child[i] + MFPath.useparator;
            else if (returnDir) relPath = relPath + child[i];
            i++;
        }
        ;

        return prePath + relPath;
    }

    public static boolean isExists(String filepath) throws Throwable {
        File file = new File(filepath);
        if (file.exists() && file.isFile())
            return true;
        else
            return false;

    }

    public static String checkRealPath(String filepath) {
        return checkPath(filepath);
    }

    public static String deleteLastPath(String filepath) {
        String path = filepath;
        if (MFString.notNullOrEmpty(filepath)) {
            path = path.substring(0, filepath.length() - 1);
        }
        return path;
    }

    public static String checkPath(String filepath) {
        String path = filepath;
        if (MFString.notNullOrEmpty(filepath)) {
            char str = filepath.charAt(filepath.length() - 1);
            if (str != '\\' && str != '/') path = path + MFPath.fseparator;
        }
        return path;
    }

    public static String checkRealPath(String filepath, boolean andChar) {
        String path = filepath;
        if (MFString.notNullOrEmpty(filepath)) {
            char str = filepath.charAt(filepath.length() - 1);
            if (str != '\\' && str != '/') {
                if (andChar)
                    path = path + MFPath.fseparator;
            } else {
                if (!andChar)
                    path = path.substring(0, filepath.length() - 1);
            }

        }
        return path;
    }

    public static String checkURLPath(String filepath) {
        String path = filepath;
        if (MFString.notNullOrEmpty(filepath)) {
            char str = filepath.charAt(filepath.length() - 1);
            if (str != '\\' && str != '/') path = path + MFPath.useparator;
        }
        return path;
    }

    public static String checkRealPath(String filepath, String newPath) {
        return checkRealPath(filepath) + newPath;
    }

    public static String checkURLPath(String filepath, String newPath) {
        return checkURLPath(filepath) + newPath;
    }

    public static String getRealWebPath(HttpServletRequest request) throws Throwable {
        return request.getSession().getServletContext().getRealPath("/");

    }

    public static String getRealBinPath() throws Throwable {
        //System.out.println(System.getProperty("user.dir"));
        //System.out.println(System.getProperty("user.home"));
        File directory = new File(".");
        return directory.getCanonicalPath();

    }

    public static String getUrlToRealPath(String url) throws Throwable {
        if (MFString.notNullOrEmpty(url)) {
            url = url.replace(MFPath.useparatorChar, MFPath.fseparatorchar);
        }
        return url;
    }

    public static String getRealToUrlPath(String url) throws Throwable {
        if (MFString.notNullOrEmpty(url)) {
            url = url.replace(MFPath.fseparatorchar, MFPath.useparatorChar);
        }
        return url;
    }

    public static String getURLWebPath(HttpServletRequest request) throws Throwable {

        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
        return basePath;
    }


    public static String getClassPath() throws Throwable {
        URL path = Thread.currentThread().getContextClassLoader().getResource("");
        String src = path.toString();
        if (src.length() > 0) {
            try {
                src = URLDecoder.decode(path.getPath(), "UTF-8"); //注意编码和输入时一致
                src = src.substring(1, src.length() - 1);
                //System.out.print(src);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        return src;

    }


    private static String readProp() {
        //ppath=ppath.substring(0,(ppath.lastIndexOf("\\classes") + 1)) + "/WEB-INF/prop/db.properties";
        URL path = Thread.currentThread().getContextClassLoader().getResource("");
        return path.getPath();
    }

    public static String getClassFile(String fileName) {
        return MFPath.getDirFromClassLoader() + MFPath.fseparator + fileName;
    }

    public static String getDirFromClassLoader() {
        try {
            String path = MFPath.class.getName().replace(".", "/");
            path = "/" + path + ".class";
            URL url = MFPath.class.getResource(path);
            String jarUrl = url.getPath();
            File file = null;
            if (jarUrl.startsWith("file:")) {

                //System.out.println("file::"+jarUrl);
                if (jarUrl.length() > 5) {

                    jarUrl = jarUrl.substring(5);
                }
                jarUrl = jarUrl.split("!")[0];
                file = new File(jarUrl);
                file = file.getParentFile();
                //System.out.println(file.getParent());
            } else {
                //System.out.println("file::"+jarUrl);
                jarUrl = MFPath.class.getResource("/").toString().substring(5);
                file = new File(jarUrl);
            }

            //System.out.println(file.getParent());
            return URLDecoder.decode(file.getParent(), "UTF-8");

        } catch (Exception e) {
        }
        return null;
    }

    public static String getDirFromLib() {
        String path = MFPath.getDirFromClassLoader();
        path = path + MFPath.fseparator + "lib" + MFPath.fseparator;
        return path;
    }

}
